/*
 * @description: 
 * @version: 1.0.1
 * @Author: xuqiulin
 * @Date: 2021-06-03 21:24:31
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-06-04 17:26:55
 */
var net = require('net');

var server = net.createServer();// 创建服务器套接字
var clients = {};// 记录连接的客户端套接字
// 客户端连接事件
server.on('connection', function(client){
	client.name = client.remoteAddress + ':' + client.remotePort;
	console.log(`客户端[${client.name}]连接成功...`);

	client.write(`我是小白菜服务器...`);
	clients[client.name] = client;
    // 接受客户端发来的消息
	client.on('data', function(data){
        console.log(`[${client.name}]:${data.toString()}`);
        // 广播消息给每一个客户端
		broadcast(data.toString(), client);
	});
    // 客户端关闭连接
	client.on('close', function() {
        delete clients[client.name];
	});
    // 客户端和服务端连接错误
	client.on('error', function(error) {
  		console.log(client.name, error);
	});
});

function broadcast(msg, client){
	var cleanup = [];
	for(var key in clients){
        const clientT = clients[key];
        if (clientT.writable){
            clientT.write(`[${client.name}]:${msg}`);
        } else {
            cleanup.push(clientT.name);
            clientT.destroy();
        }
	}
	for (var key of cleanup) {
		delete clients[key];
	}
}
// 服务器开始监听，等待客户端连接
server.listen(8888, '127.0.0.1');

console.log('服务器开始监听127.0.0.1:8888...');
